package br.com.extrajudicial.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Hibernate;
import br.com.caelum.vraptor.view.Results;
import br.com.extrajudicial.dao.ItemDao;
import br.com.extrajudicial.interceptors.RequireUser;
import br.com.extrajudicial.models.Item;

@Resource
public class ItemsController {
	
	@Autowired private ItemDao itemDao;
	@Autowired private Validator validator;
	@Autowired private Result result;
	
	@Get @Path("/items")
	public List<Item> items() {
		return this.itemDao.listAll();
	}
	
	@Get @Path("/items/add")
	@RequireUser
	public void add() { }
	
	@Post @Path("/items")
	public void save(Item item) {
		this.validator.addAll(Hibernate.validate(item));
		this.validator.onErrorUse(Results.page()).of(ItemsController.class).add();
		this.itemDao.save(item);
		redirectToItems();
	}
	
	@Get @Path("/items/{id}/edit")
	@RequireUser
	public Item edit(Long id) {
		return this.itemDao.load(id);
	}
	
	@Put @Path("/items")
	@RequireUser
	public void update(Item item) {
		this.validator.addAll(Hibernate.validate(item));
		this.validator.onErrorUse(Results.page()).of(ItemsController.class).edit(item.getId());
		this.itemDao.update(item);
		redirectToItems();
	}

	@Delete @Path("/items/{id}")
	@RequireUser
	public void delete(Long id) {
		Item item = this.itemDao.load(id);
		this.itemDao.delete(item);
		redirectToItems();
	}
	
	@Get @Path("/items/search")
	public List<Item> search(String name) {
		this.result.include("name", name);
		return this.itemDao.search(name);
	}

	private void redirectToItems() {
		this.result.redirectTo(ItemsController.class).items();
	}
	
}
